import 'package:app/api/flow/index.dart';
import 'package:app/components/index.dart';
import 'package:app/util/StringUtils.dart';
import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;

import '../../util/AndroidChannel.dart';

class FlowProcess extends StatefulWidget {
  const FlowProcess({super.key});

  @override
  State<FlowProcess> createState() => _FlowProcessState();
}

class _FlowProcessState extends State<FlowProcess> {
  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  final FocusNode _firstFocusNode = FocusNode();
  final FocusNode _locationFocusNode = FocusNode();

  // 编码
  String _code = "";
  // 暂存位置
  String _location = "";
  // 数据
  dynamic _data;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      FocusScope.of(context).requestFocus(_firstFocusNode);
    });
  }

  void hideKeyBorder() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus?.unfocus();
    }
  }

  void scan(String key) async{
    String? qrCode = await scanner.scan();
    if (key == 'code') {
      setState(() => _code = qrCode.toString());
    } else if (key == 'location') {
      setState(() => _location = qrCode.toString());
    }
  }

  /// 回车处理
  handleEntry(String value){
    setState((){
      _code = value;
      _data = null;
    });
    search(value);
  }

  /// 查找数据
  void search(value){
    FlowProcessApi.of(context).materialFlow(value??_code).then((res){
      if(StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)){
        setState(() => _data =  res.data['data']);
        if(StringUtils.isNotNull(res.data['data']['message'])){
          Error.of(context).show(res.data['data']['message']);
        }
      }
    });
  }

  /// 直投操作
  void directPut() {
    Map<String, String> data = {
      'companyCode': _data['companyCode'],
      'orderNo': _data['shopOrder'],
      'qty': _data['receiveQty'],
      'receiveDeptCode': _data['deptCode']
    };
    FlowProcessApi.of(context).directPut(data).then((res) {
      if (StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)) {
        Success.of(context).show('直投成功');
      }
    });
  }

  /// 暂存操作
  void stash() {
    if (StringUtils.isNull(_location)) {
      Error.of(context).show('请先扫描暂存位置');
      return;
    }
    Map<String, String> param = {
      'orderNo': _data['shopOrder'],
      'itemCode': _data['itemCode'],
      'itemName': _data['itemName'],
      'qty': _data['receiveQty'],
      'workNo': _data['workNo'],
      'unitName': _data['unitName'],
      'status': '无需求',
      'location': _location,
    };
    FlowProcessApi.of(context).stash(param).then((res) {
      Success.of(context).show('暂存成功');
      setState(() {
        _location = '';
      });
      handleEntry(_code);
    });
  }

  /// 报工周转操作
  void takeOver() {
    Map<String, String> data = {
      'taskNo': _code,
      'sourceMethod': _data['sourceMethod'],
    };
    FlowProcessApi.of(context).takeOver(data).then((res) {
      if (StringUtils.isNotNull(res.data) && StringUtils.isNotNull(res)) {
        Success.of(context).show('报工周转成功');
        search(_code);
      }
    });
  }

  void printLabel() {
    Confirm.of(context).show('确定要打印单据么？', () {
      // 1. 初始化通道
      AndroidChannel.initChannels();
      // 2. 调用通道方法
      AndroidChannel.printHandler(_data).then((res) {
        // print("res${res}");
        Error.of(context).show('打印失败');
      });
      Navigator.pop(context);
    });
  }

  void printTakeLabel() {
    Confirm.of(context).show('确定要打印单据么？', () {
      // 1. 初始化通道
      AndroidChannel.initChannels();
      // 2. 调用通道方法
      AndroidChannel.printTakeHandler(_data).then((res) {
        // print("res${res}");
        Error.of(context).show('打印失败');
      });
      Navigator.pop(context);
    });
  }

  /// 获取操作按钮
  Widget getButton(){
    if (StringUtils.isNull(_data)) {
      return Container();
    }
    if(_data['mode'] != 'take_over' && _data['orderStatus'] == 'E'
        && (StringUtils.isNull(_data['reqQty']) || _data['reqQty'] == "0")
        && StringUtils.isNull(_data['message'])){
      // 无需求的情况，提供暂存的功能
      return SizedBox(
          width: MediaQuery.of(context).size.width,
          child: Padding(
            padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
            child: Button(
              onPressed: stash,
              label: '暂存',
              height: 60,
              fontSize: 18,
            ),
          )
      );
    }else if(_data['mode'] != 'take_over' && _data['orderStatus'] == 'C'){
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: printLabel,
            label: '打印',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    } else if (_data['mode'] != 'take_over' && _data['orderStatus'] != 'C' && StringUtils.isNull(_data['message'])) {
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: directPut,
            label: '直投',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    } else if(_data['mode'] == 'take_over' && StringUtils.isNotNull(_data['message'])){
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: printTakeLabel,
            label: '打印',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    } else if(_data['mode'] == 'take_over' && StringUtils.isNull(_data['message'])){
      return SizedBox(
        width: MediaQuery.of(context).size.width,
        child: Padding(
          padding: const EdgeInsets.only(top: 10, left: 20, right: 20),
          child: Button(
            onPressed: takeOver,
            label: '报工周转',
            height: 60,
            fontSize: 18,
          ),
        ),
      );
    }
    return Container();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      appBar: AppBars(context: context, title: '流向处理'),
      body: GestureDetector(
        onTap: hideKeyBorder,
        child: Container(
          color: const Color.fromARGB(255, 245, 245, 245),
          child: Column(
            children: [
              Group(
                context: context,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Forms(
                      formKey: _formKey,
                      formItem:
                      StringUtils.isNotNull(_data) && _data['orderStatus'] == 'E' && (StringUtils.isNull(_data['reqQty']) || _data['reqQty'] == "0")
                          ? [
                              FormItem(
                                type: 'input',
                                focusNode: _firstFocusNode,
                                labelText: '任 务 号',
                                labelWidth: 100,
                                placeholder: '请输入或扫描任务号',
                                filedName: 'code',
                                value: _code,
                                icon: const Icon(Icons.qr_code_scanner_rounded),
                                onEntry: (value) => {handleEntry(value)},
                                iconOnTap: () => scan('code'),
                                rules: const {
                                  'code': [
                                    {'required': true, 'message': '任务号不能为空'}
                                  ]
                                },
                              ),
                              FormItem(
                                focusNode: _locationFocusNode,
                                type: 'input',
                                labelText: '暂存位置',
                                labelWidth: 100,
                                placeholder: '请扫描货架位置',
                                filedName: 'location',
                                value: _location,
                                // enabled: false,
                                icon: const Icon(Icons.qr_code_scanner_rounded),
                                iconOnTap: () => scan('location'),
                                onChange: (value) {
                                  setState(() {
                                    _location = value;
                                  });
                                },
                              )
                            ]
                          : [
                              FormItem(
                                type: 'input',
                                focusNode: _firstFocusNode,
                                labelText: '任 务 号',
                                labelWidth: 100,
                                placeholder: '请输入或扫描任务号',
                                filedName: 'code',
                                value: _code,
                                icon: const Icon(Icons.qr_code_scanner_rounded),
                                onEntry: (value) => {handleEntry(value)},
                                iconOnTap: () => scan('code'),
                                rules: const {
                                  'code': [
                                    {'required': true, 'message': '任务号不能为空'}
                                  ]
                                },
                              )
                            ],
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListContainer(
                  title: StringUtils.isNotNull(_data) && _data['mode'] == 'take_over' ? '报工周转明细' : '流向明细',
                  length: 1,
                  children: (index){
                    return [
                      Offstage(
                        offstage: (StringUtils.isNotNull(_data) && _data['mode'] != 'take_over' && _data['orderStatus'] != 'C') ? false : true,
                        child: Column(
                          children: [
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '任务编号：',
                                  value: _data?['shopOrder'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '公司编号：',
                                  value: _data?['companyCode'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '零件编号：',
                                  value: _data?['itemCode'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '交接数量：',
                                  value: _data?['receiveQty'],
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '零件名称：',
                                  value: _data?['itemName'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '需求数量：',
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  value: _data?['reqQty'] ?? "0",
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Offstage(
                        offstage: StringUtils.isNotNull(_data) && _data['orderStatus'] == 'C' ? false : true,
                        child: Column(
                          children: [
                            ListTitle(context: context, label: _data?['customerName'],),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '目标工位：',
                                  value: _data?['wcName'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(items: [
                              HorizontalItem(
                                flex: 1,
                                label: '工  作  令：',
                                value: _data?['workNo'],
                                fontWeight: FontWeight.w600,
                              ),
                            ]),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '任务编号：',
                                  value: _data?['shopOrder'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '交接数量：',
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  value: _data?['orderQty'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '后工序开始时间：',
                                  value: _data?['startDate'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '需求数量：',
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  value: _data?['planQty'] ?? "0",
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                      Offstage(
                        offstage: StringUtils.isNotNull(_data) && _data['mode'] == 'take_over' ? false : true,
                        child: Column(
                          children: [
                            // ListTitle(context: context, label: _data?['customerName'],),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '工  作  令：',
                                  value: _data?['workNo'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '目标工位：',
                                  value: _data?['wcName'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '任务编号：',
                                  value: _data?['shopOrder'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                            Horizontal(
                              items: [
                                HorizontalItem(
                                  flex: 1,
                                  label: '后工序开始时间：',
                                  value: _data?['startDate'],
                                  fontWeight: FontWeight.w600,
                                ),
                                HorizontalItem(
                                  flex: 1,
                                  label: '交接数量：',
                                  valueBackground: Colors.lightBlueAccent,
                                  fontColor: Colors.white,
                                  value: _data?['orderQty'],
                                  fontWeight: FontWeight.w600,
                                ),
                              ],
                            ),
                          ],
                        ),
                      )
                    ];
                  },
                ),
              ),
              getButton()
            ],
          ),
        ),
      ),
    );
  }
}
